package com.jingxi.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingxi.common.pojo.JingXiResult;
import com.jingxi.common.util.IDUtils;
import com.jingxi.mapper.TbContentCategoryMapper;
import com.jingxi.mapper.TbContentMapper;
import com.jingxi.model.TbContentCategory;
import com.jingxi.model.TbContentCategoryExample;
import com.jingxi.model.TbContentCategoryExample.Criteria;
import com.jingxi.model.TbContentExample;

@Service
public class ContentCatServiceImpl implements ContentCatService {

	@Autowired
	private TbContentCategoryMapper tbContentCatMapper;

	@Autowired
	private TbContentMapper tbContentMapper;

	@SuppressWarnings("finally")
	@Override
	public List<TbContentCategory> getContentCatList(long parentId) {
		TbContentCategoryExample example = new TbContentCategoryExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbContentCategory> list = tbContentCatMapper.selectByExample(example);
		return list;
	}

	@Override
	public JingXiResult createContentCat(long parentId, String name) {
		Date date = new Date();
		long id = IDUtils.genItemId();// 生成ID
		TbContentCategory tbContentCategory = new TbContentCategory();
		tbContentCategory.setId(id);
		tbContentCategory.setParentId(parentId);
		tbContentCategory.setName(name);
		tbContentCategory.setCreated(date);
		tbContentCategory.setStatus(1);
		tbContentCategory.setSortOrder(1);
		tbContentCategory.setUpdated(date);
		tbContentCategory.setIsParent(false);//不是父类目
		tbContentCatMapper.insertSelective(tbContentCategory);
		return JingXiResult.ok(tbContentCategory);
	}

	@Override
	public JingXiResult updateContentCat(long id, String name) {
		TbContentCategory tbContentCategory = new TbContentCategory();
		tbContentCategory.setId(id);
		tbContentCategory.setName(name);// 更新分类名字
		tbContentCatMapper.updateByPrimaryKeySelective(tbContentCategory);
		return JingXiResult.ok();
	}

	@Override
	public JingXiResult deleteContentCat(long id) {
		// 删除该目录下内容
		TbContentCategoryExample example = new TbContentCategoryExample();
		example.createCriteria().andParentIdEqualTo(id);
		// 删除该目录
		tbContentCatMapper.deleteByPrimaryKey(id);
		// 判断该目录是否还有同胞
		long count = tbContentCatMapper.countByExample(example);
		// 如果没有则其父亲的isParent值改为0
		if (count == 0) {
			TbContentCategory cc = new TbContentCategory();
			cc.setId(id);
			cc.setIsParent(false);
			tbContentCatMapper.updateByPrimaryKey(cc);
		}
		// 删除已添加的内容
		TbContentExample example2 = new TbContentExample();
		example2.createCriteria().andCategoryIdEqualTo(id);
		tbContentMapper.deleteByExample(example2);
		return JingXiResult.ok();
	}

}
